package com.firexmoon.hoverclock

import android.app.Service
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.TextView
import java.util.Locale

class FloatingService : Service() {
    
    companion object {
        // 用于传递关闭服务的动作
        const val ACTION_STOP_SERVICE = "com.firexmoon.hoverclock.STOP_SERVICE"
    }
    
    private var windowManager: WindowManager? = null
    private var floatingView: View? = null
    private var params: WindowManager.LayoutParams? = null
    
    private var isTimerRunning = false
    private var startTimeMillis: Long = 0
    private val handler = Handler(Looper.getMainLooper())
    
    private lateinit var tvTimer: TextView
    private lateinit var btnStartStop: Button
    private lateinit var btnClose: Button
    
    private val timerRunnable = object : Runnable {
        override fun run() {
            updateTimerDisplay()
            handler.postDelayed(this, 1000)
        }
    }
    
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // 检查是否是停止服务的动作
        if (intent != null && ACTION_STOP_SERVICE == intent.action) {
            stopSelf()
            return START_NOT_STICKY
        }
        
        return super.onStartCommand(intent, flags, startId)
    }
    
    override fun onCreate() {
        super.onCreate()
        
        // 初始化WindowManager
        windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
        
        // 创建布局参数
        params = WindowManager.LayoutParams().apply {
            width = WindowManager.LayoutParams.WRAP_CONTENT
            height = WindowManager.LayoutParams.WRAP_CONTENT
            
            // 根据系统版本设置窗口类型
            type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            }
            
            flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            format = PixelFormat.TRANSLUCENT
            gravity = Gravity.TOP or Gravity.START
            x = 100
            y = 100
        }
        
        // 加载布局
        floatingView = LayoutInflater.from(this).inflate(R.layout.layout_floating_timer, null)
        
        // 初始化视图
        tvTimer = floatingView!!.findViewById(R.id.tvTimer)
        btnStartStop = floatingView!!.findViewById(R.id.btnStartStop)
        btnClose = floatingView!!.findViewById(R.id.btnClose)
        
        // 设置按钮点击事件
        btnStartStop.setOnClickListener {
            if (isTimerRunning) {
                // 现在这个按钮功能改为复位而不是暂停
                resetTimer()
                btnStartStop.text = "开始"
            } else {
                startTimer()
                btnStartStop.text = "复位"
            }
        }
        
        // 设置关闭按钮点击事件
        btnClose.setOnClickListener {
            stopSelf()
        }
        
        // 设置拖动事件
        setupDragListener()
        
        // 将视图添加到窗口
        windowManager?.addView(floatingView, params)
    }
    
    private fun setupDragListener() {
        floatingView?.setOnTouchListener(object : View.OnTouchListener {
            private var initialX = 0
            private var initialY = 0
            private var initialTouchX = 0f
            private var initialTouchY = 0f
            
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                when (event?.action) {
                    MotionEvent.ACTION_DOWN -> {
                        // 记录初始位置
                        initialX = params?.x ?: 0
                        initialY = params?.y ?: 0
                        initialTouchX = event.rawX
                        initialTouchY = event.rawY
                        return true
                    }
                    MotionEvent.ACTION_MOVE -> {
                        // 计算偏移量并更新位置
                        params?.x = initialX + (event.rawX - initialTouchX).toInt()
                        params?.y = initialY + (event.rawY - initialTouchY).toInt()
                        
                        // 更新视图位置
                        windowManager?.updateViewLayout(floatingView, params)
                        return true
                    }
                }
                return false
            }
        })
    }
    
    private fun startTimer() {
        isTimerRunning = true
        startTimeMillis = System.currentTimeMillis()
        handler.post(timerRunnable)
    }
    
    private fun stopTimer() {
        isTimerRunning = false
        handler.removeCallbacks(timerRunnable)
    }
    
    private fun resetTimer() {
        stopTimer()
        updateTimerDisplay()
        btnStartStop.text = "开始"
    }
    
    private fun updateTimerDisplay() {
        if (isTimerRunning) {
            val currentTimeMillis = System.currentTimeMillis()
            val elapsedTimeMillis = currentTimeMillis - startTimeMillis
            
            val seconds = (elapsedTimeMillis / 1000).toInt() % 60
            val minutes = (elapsedTimeMillis / 1000 / 60).toInt()
            
            tvTimer.text = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds)
        } else {
            tvTimer.text = "00:00"
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 停止计时器
        stopTimer()
        
        // 移除悬浮窗
        floatingView?.let { windowManager?.removeView(it) }
    }
} 